from pprint import pprint
from typing import List


class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        if n<=0:
            return []
        matrix = [[0] * n for _ in range(n)]

        # 设定边界
        top = 0
        left = 0
        bottom = n - 1
        right = n - 1
        n = 1
        while top <= bottom and left <= right:
            # 左->右
            for i in range(left, right + 1):
                matrix[top][i] = n
                n += 1
            top += 1

            # 上->下
            for i in range(top, bottom + 1):
                matrix[i][right] = n
                n += 1

            right -= 1

            # 右->左
            for i in range(right, left - 1, -1):
                matrix[bottom][i] = n
                n += 1
            bottom -= 1

            # 下->上
            for i in range(bottom, top - 1, -1):
                matrix[i][left] = n
                n += 1
            left += 1

        return matrix

pprint(Solution().generateMatrix(3))
sys.s